﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace LingDingSoft
{
    /// <summary>
    /// 配置文件获取操作
    /// </summary>
    public class AppConfig
    {
        public static string GetSecret()
        {
            string rRts = "c3a6eeb79750f79f73c7a0722568ffbeccfabf18";
            return rRts;
        }
        public static string GetAppKey()
        {
            string rRts = "fkH9ANkaLB";
            return rRts;
        }
        public static Encoding GetEncoding()
        {

            return Encoding.UTF8;
        }
        public static string GetAPIUrl()
        {
            return "https://open-api-sandbox.shop.ele.me/api/v1/";
        }
        public static string GetTokenUrl()
        {
            return "https://open-api-sandbox.shop.ele.me/token";
        }
        public static string GetCallBackUrl()
        {
            return "http://ceshi.chineseu.cn/callback";
        }
        /// <summary>
        /// 获取Token注意处理过期问题
        /// </summary>
        /// <returns></returns>
        public static Model.TokenModel GetToken()
        {
            Model.TokenModel token = null;
            string jsonPath = "";

            //以下是从文件中获取，实际运用时需要换成数据库
            if (HttpContext.Current != null)
            {
                jsonPath = HttpContext.Current.Server.MapPath("tokenjson.txt");

            }
            else
            {
                jsonPath = AppDomain.CurrentDomain.BaseDirectory + "tokenjson.txt";
            }
            if (System.IO.File.Exists(jsonPath))
            {
                var json = System.IO.File.ReadAllText(jsonPath);
                if (!string.IsNullOrEmpty(json))
                {
                    token = Newtonsoft.Json.JsonConvert.DeserializeObject<Model.TokenModel>(json);
                }
            }




            if (token == null)
            {
                throw new NullReferenceException("未找到Token信息");
            }

            //以下自行处理
            //判断是否过期   前一次获取的时间  + new TimeSpan(0,0, token.expires_in) <当前时间
            if (false)
            {
                //刷新你的token
                Service.AccessTokenService Svc = new Service.AccessTokenService();
                var refToken= Svc.GetRefreshToken(token.refresh_token);
                if (refToken!=null)
                {
                    //保存你的token
                    token = refToken;
                }
                else
                {
                    //异常处理
                }

            }


            return token;
        }

    }
}
